﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Proggy.Web.Cms.AppHelpers;
using WURFL;

namespace Proggy.Web.Cms.Context
{
    /// <summary>
    /// Request browser context
    /// </summary>
    public class BrowserContext
    {
        /// <summary>
        /// True if, for example, mobile phone or pda
        /// </summary>
        public bool IsMobile { get; set; }

        /// <summary>
        /// True if, for example, iPad
        /// </summary>
        public bool IsTablet { get; set; }

        /// <summary>
        /// Wurfl device - see http://wurfl.sourceforge.net/help_doc.php for capabilities
        /// </summary>
        public IDevice WurflDevice { get; set; }

        /// <summary>
        /// Current browser context
        /// </summary>
        public static BrowserContext Current
        {
            get
            {
                if (!CurrentIsSet())
                {
                    if (
                        StartupManager.WurflManager != null && 
                        HttpContext.Current != null && 
                        HttpContext.Current.Request != null && 
                        !string.IsNullOrEmpty(HttpContext.Current.Request.UserAgent))
                    {
                        // ctx
                        var ctx = new BrowserContext();

                        // device
                        var device = StartupManager.WurflManager.GetDeviceForRequest(HttpContext.Current.Request.UserAgent);

                        // SET ctx
                        ctx.WurflDevice = device;
                        ctx.IsTablet = Convert.ToBoolean(device.GetCapability("is_tablet"));
                        ctx.IsMobile = Convert.ToBoolean(device.GetCapability("is_wireless_device")) && !ctx.IsTablet;
                        

                        // add
                        HttpContext.Current.Items.Add(_ctx_Key, ctx);
                        HttpContext.Current.Items.Add(_ctx_Set_Key, true);

                        // set
                        _current = (BrowserContext)HttpContext.Current.Items[_ctx_Key];
                    }
                }

                return _current;
            }
            set {
                _current = value;
            }
        }        

        // private
        private static BrowserContext _current;
        private static bool CurrentIsSet() { 
            return
                HttpContext.Current != null &&
                HttpContext.Current.Items != null &&
                HttpContext.Current.Items[_ctx_Set_Key] != null &&
                Convert.ToBoolean(HttpContext.Current.Items[_ctx_Set_Key]);
        }
        private const string _ctx_Key = "BROWSER_CONTEXT_KEY";
        private const string _ctx_Set_Key = "BROWSER_CONTEXT_SET_KEY";
    }
}
